package com.dl.utils;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.List;

/**
 * 原始文件上传工具类
 */
public class UploadUtils {

    public static void upload(HttpServletRequest req, String uploadPath){

        //判断上传的是文件表单还是普通表单
        if (!ServletFileUpload.isMultipartContent(req)){
            System.out.println("不是文件表单");
            return;
        }

        //1.创建DiskFileItemFactory对象，处理文件上传路径和大小
        DiskFileItemFactory factory = getDiskFileItemFactory();

        //2.获取ServletFileUpload
        ServletFileUpload upload = getServletFileUpload(factory);

        //3.处理上传的文件
        uploadParseRequest(upload, req, uploadPath);
    }

    public static DiskFileItemFactory getDiskFileItemFactory(){
        File temporaryFile = new File("F:\\DL\\上传");
        if (!temporaryFile.exists()){
            temporaryFile.mkdir();
        }
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //设置缓冲区，如果大于缓冲区，放入临时文件中，单位字节
        factory.setSizeThreshold(1024 * 1024 * 5);
        factory.setRepository(temporaryFile);
        return factory;
    }

    public static ServletFileUpload getServletFileUpload(DiskFileItemFactory factory){
        ServletFileUpload upload = new ServletFileUpload(factory);
/*        upload.setProgressListener(new ProgressListener() {
            @Override
            public void update(long pBytesRead, long pContentLength, int pItems) {
                //System.out.println("总大小："+ pContentLength + "-已上传" + pBytesRead);
                double progress = pBytesRead / (double)pContentLength;
                DecimalFormat df = new DecimalFormat("0.00%");
                String percent = df.format(progress);
                System.out.println("上传进度："+ percent + "%");
            }
        });*/
        //处理乱码问题
        upload.setHeaderEncoding("utf-8");
        //设置单个文件最大值
        upload.setFileSizeMax(1024 * 1024 * 5);
        //设置总共能上传最大值
        upload.setSizeMax(1024 * 1024 * 10);
        return upload;
    }

    public static void uploadParseRequest(ServletFileUpload upload, HttpServletRequest request, String uploadPath){
        //解析请求，封装成一个FileItem对象
        FileOutputStream fos = null;
        InputStream inputStream = null;
        try {
            List<FileItem> fileItems = upload.parseRequest(request);
            //fileItem每一个表单对象
            for (FileItem fileItem : fileItems) {
                if (fileItem.isFormField()){
                    //普通控件
                    String name = fileItem.getFieldName();
                    String value = fileItem.getString("utf-8");
                    System.out.println(name + ":" + value);
                }else{
                    //=====================处理文件=====================
                    //获得文件名字
                    String fileName = fileItem.getName();
                    if (fileName.trim().equals("")){
                        continue;
                    }
                    System.out.println("=====================文件信息=====================");

                    //获得文件后缀
                    String suffixName = fileName.substring(fileName.lastIndexOf(".") + 1);
                    //获得文件大小
                    long size = fileItem.getSize();
                    //获得文件类型
                    String type = fileItem.getContentType();
                    //计算文件大小，转换相应的单位
                    String calculateSize = calculateSize(size);
                    System.out.println("[文件名:" + fileName +
                                    "---文件后缀:" + suffixName +
                                    "---文件类型:" + type +
                                    "---文件大小:" + calculateSize + "("+ size +"字节)]");
                    //=====================存放地址=====================
                    //使用uuid保证文件名唯一
                    String uuidPath = UUIDUtils.getUUID8();

                    String realPath = uploadPath + "/" + uuidPath;
                    File realPathFile = new File(realPath);
                    if (!realPathFile.exists()){
                        realPathFile.mkdir();
                    }
                    //=====================文件传输=====================

                    inputStream = fileItem.getInputStream();

                    fos = new FileOutputStream(realPath +"/"+fileName);
                    //创建缓冲区
                    byte[] buffer = new byte[1024 * 1024];

                    int len = 0;
                    //如果大于0说明还存在数据
                    while ((len=inputStream.read(buffer))>0){
                        fos.write(buffer,0,len);
                    }
                    fileItem.delete();
                }
            }
        } catch (FileUploadException | IOException e) {
            e.printStackTrace();
        } finally {
            //关闭流
            try {
                if (fos != null) {
                    fos.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static String calculateSize(long fileLong){
        String size = "";
        DecimalFormat df = new DecimalFormat("0.00");
        if (fileLong < (1024 * 1024)){
            size = df.format((double) fileLong / 1024) + "KB";
        }else{
            size = df.format((double) fileLong / 1024 / 1024) + "MB";
        }
        return size;
    }

}
